package com.typing.battle.activity;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

import org.json.JSONObject;

import com.typing.battle.R;
import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.value.ServerComunicationDTO;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class TypingBattleMemberUpdateActivity extends TypingBattleRootActivity{
	private ImageView img;
	private TextView phone,email;
	private EditText name,descript,age;
	private EditText lastPwd,newPwd,repeatPwd;
	private Button pwd,save;
	private String password;
	private PreferenceMgr mgr;
	private String phoneNum;
	private static final int PICK_FROM_CAMERA = 0; 
	private static final int PICK_FROM_ALBUM = 1; 
	private static final int CROP_FROM_CAMERA = 2; 
	 
	private Uri mImageCaptureUri; 
	private ImageView mPhotoImageView;
	private Context mContext;
	private Button logout;
	private RadioButton sex_m;
	private RadioButton sex_f;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.battle_member_update);
		mContext = this;
		mgr = PreferenceMgr.getInstance(this);
		
//		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//		phoneNum = tm.getLine1Number();		
		    	
		img = (ImageView)findViewById(R.id.img_user);
		phone = (TextView)findViewById(R.id.data_phone);		
		email = (TextView)findViewById(R.id.data_email);		
		name = (EditText)findViewById(R.id.input_update_name);
		descript = (EditText)findViewById(R.id.input_update_descript);
		age = (EditText)findViewById(R.id.input_update_age);
		pwd = (Button)findViewById(R.id.btn_change_password);
		save = (Button)findViewById(R.id.btn_change_save);
		logout = (Button)findViewById(R.id.btn_logout);
		sex_m = (RadioButton)findViewById(R.id.input_sex_m);
		sex_f = (RadioButton)findViewById(R.id.input_sex_f);

		//img.setBitmap(Result);
		img.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	 DialogInterface.OnClickListener cameraListener = new DialogInterface.OnClickListener() 
            	    { 
            	      @Override 
            	      public void onClick(DialogInterface dialog, int which) 
            	      { 
            	        doTakePhotoAction(); 
            	      } 
            	    }; 
            	     
            	    DialogInterface.OnClickListener albumListener = new DialogInterface.OnClickListener() 
            	    { 
            	      @Override 
            	      public void onClick(DialogInterface dialog, int which) 
            	      { 
            	        doTakeAlbumAction(); 
            	      } 
            	    }; 
            	     
            	    DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() 
            	    { 
            	      @Override 
            	      public void onClick(DialogInterface dialog, int which) 
            	      { 
            	        dialog.dismiss(); 
            	      } 
            	    }; 
            	     
            	    new AlertDialog.Builder(mContext) 
            	      .setTitle("업로드할 이미지 선택") 
            	      .setPositiveButton("사진촬영", cameraListener) 
            	      .setNeutralButton("앨범선택", albumListener) 
            	      .setNegativeButton("취소", cancelListener) 
            	      .show(); 

            }
        });
		
		pwd.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	showDialog(0);
            }
        });
		
		save.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	saveUpdate();
            }
        });
		logout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				logOut();
			}
		});
		getUserInfo();
	}
	
	private void getUserInfo(){
		
		ServerComunicationDTO dto = new ServerComunicationDTO();
    	dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
    	dto.setUserPassword(mgr.getData(PreferenceMgr.USER_PASSWORD_KEY, ""));
    	
    	dto.setUserName(name.getText().toString());
    	dto.setUserDescription(descript.getText().toString());
    	dto.setActionType(ServerComunicationUtil.TYPE_MEMBER_DETAIL);
    	dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
    	try{
    		ServerComunicationUtil.serverAction(dto,this,this);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	//mgr.setData(PreferenceMgr.USER_EMAIL_KEY, dto.getUserEmail());
//    	if(password != null){
//    		mgr.setData(PreferenceMgr.USER_PASSWORD_KEY, dto.getUserPassword());
//    	}
//    	mgr.setData(PreferenceMgr.USER_NAME_KEY, dto.getUserName());
//    	mgr.setData(PreferenceMgr.USER_DESCRIPT_KEY, dto.getUserDecription());
	}
	
	private void saveUpdate(){
		email = (TextView)findViewById(R.id.data_email);		
		name = (EditText)findViewById(R.id.input_update_name);
		descript = (EditText)findViewById(R.id.input_update_descript);
		age = (EditText)findViewById(R.id.input_update_age);
		sex_m = (RadioButton)findViewById(R.id.input_sex_m);
		
		ServerComunicationDTO dto = new ServerComunicationDTO();
    	dto.setUserEmail(email.getText().toString());
    	if(password != null){
    		dto.setNewPassword(password);
    	}
    	dto.setUserPassword(mgr.getData(PreferenceMgr.USER_PASSWORD_KEY, ""));
    	//dto.setUserRegKey(mgr.getData(PreferenceMgr.REGISTRATION_KEY, ""));
    	dto.setUserName(name.getText().toString());
    	dto.setUserDescription(descript.getText().toString());
    	dto.setUserAge(age.getText().toString());
    	dto.setUserSex(sex_m.isChecked() ? "M":"F");
    	dto.setActionType(ServerComunicationUtil.TYPE_MEMBER_UPDATE);
    	dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
    	try{
    		ServerComunicationUtil.serverAction(dto,this,this);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	//mgr.setData(PreferenceMgr.USER_EMAIL_KEY, dto.getUserEmail());
//    	if(password != null){
//    		mgr.setData(PreferenceMgr.USER_PASSWORD_KEY, dto.getUserPassword());
//    	}
//    	mgr.setData(PreferenceMgr.USER_NAME_KEY, dto.getUserName());
//    	mgr.setData(PreferenceMgr.USER_DESCRIPT_KEY, dto.getUserDecription());
	}
	private void showNotify(String msg) {
		Toast toast = Toast.makeText(this, msg , Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
		toast.show();
	} 
	
	private void logOut() {
		mgr.setData(PreferenceMgr.USER_EMAIL_KEY, "");
		Toast toast = Toast.makeText(this, getString(R.string.toast_logout_complete) , Toast.LENGTH_SHORT);
//		toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
		toast.show();
		Intent intent = new Intent(mContext,TypingBattleLoginActivity.class);
		startActivity(intent);
		finish();
	}	
	
	@Override
    protected Dialog onCreateDialog(int id) {
		LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.dialog_password, null);
        lastPwd = (EditText)textEntryView.findViewById(R.id.input_last_password); 
        newPwd = (EditText)textEntryView.findViewById(R.id.input_new_password);
        repeatPwd = (EditText)textEntryView.findViewById(R.id.input_new_password_repeat);
        return new AlertDialog.Builder(this)
            .setIcon(R.drawable.ic_launcher)
            .setTitle(R.string.title_password_dialog)
            .setView(textEntryView)
            .setPositiveButton(R.string.btn_alert_save, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	if(mgr.getData(PreferenceMgr.USER_PASSWORD_KEY, "").equals(lastPwd.getText().toString())){
                		if(newPwd.getText().toString().equals(repeatPwd.getText().toString())){
        					password = newPwd.getText().toString();
        					dialog.dismiss();	
                		}else{
                			showNotify("재입력한 패스워드가 틀립니다.");
                		}
                	}else{
                		showNotify("기존 패스워드가 맞지 않습니다.");
                	}
                    /* User clicked OK so do some stuff */
                }
            })
            .setNegativeButton(R.string.btn_alert_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	dialog.dismiss();
                    /* User clicked cancel so do some stuff */
                }
            })
            .create();
	}
	
	/**
	 * 카메라에서 이미지 가져오기
	 */
	private void doTakePhotoAction() {
		/*
		 * 참고 해볼곳 http://2009.hfoss.org/Tutorial:Camera_and_Gallery_Demo
		 * http://stackoverflow
		 * .com/questions/1050297/how-to-get-the-url-of-the-captured-image
		 * http://www.damonkohler.com/2009/02/android-recipes.html
		 * http://www.firstclown.us/tag/android/
		 */

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		// 임시로 사용할 파일의 경로를 생성
		String url = "tmp_" + String.valueOf(System.currentTimeMillis())
				+ ".jpg";
		mImageCaptureUri = Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), url));

		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
				mImageCaptureUri);
		// 특정기기에서 사진을 저장못하는 문제가 있어 다음을 주석처리 합니다.
		// intent.putExtra("return-data", true);
		startActivityForResult(intent, PICK_FROM_CAMERA);
	}

	/**
	 * 앨범에서 이미지 가져오기
	 */
	private void doTakeAlbumAction() {
		// 앨범 호출
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
		startActivityForResult(intent, PICK_FROM_ALBUM);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case CROP_FROM_CAMERA: {
			// 크롭이 된 이후의 이미지를 넘겨 받습니다.
			// 이미지뷰에 이미지를 보여준다거나 부가적인 작업 이후에
			// 임시 파일을 삭제합니다.
			final Bundle extras = data.getExtras();
			Bitmap photo = null;
			if (extras != null) {
				photo = extras.getParcelable("data");
				img.setImageBitmap(photo);
				
			}
			
			// 임시 파일 삭제
			ServerComunicationDTO dto = new ServerComunicationDTO();
	    	dto.setUserEmail(email.getText().toString());
	    	dto.setActionType(ServerComunicationUtil.TYPE_FILE_UPLOAD);
	    	dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
	    	File f = new File(mImageCaptureUri.getPath());
	    	//Log.d("image URL",mImageCaptureUri.getPath().toString());
	    	Log.d("file exists","" + f.exists());
	    	try{
	    		ServerComunicationUtil.uploadFile(mContext,photo,dto.getUserEmail());
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
			
			if (f.exists()) {
				f.delete();
			}

			break;
		}

		case PICK_FROM_ALBUM: {
			// 이후의 처리가 카메라와 같으므로 일단 break없이 진행합니다.
			// 실제 코드에서는 좀더 합리적인 방법을 선택하시기 바랍니다.

			mImageCaptureUri = data.getData();
		}

		case PICK_FROM_CAMERA: {
			// 이미지를 가져온 이후의 리사이즈할 이미지 크기를 결정합니다.
			// 이후에 이미지 크롭 어플리케이션을 호출하게 됩니다.

			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(mImageCaptureUri, "image/*");

			intent.putExtra("outputX", 90);
			intent.putExtra("outputY", 90);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, CROP_FROM_CAMERA);

			break;
		}
		}
	}
	@Override
	public void onSyncComplete(int resultCode, ServerComunicationDTO dto, Object resultObj) {
		if(resultCode == OnDataSyncCompleteListener.RESULT_SYNC_FAIL){
			if(resultObj!=null)
				ServerComunicationUtil.showNotify((String)resultObj, this);
		}else{
			if(dto.getActionType() == ServerComunicationUtil.TYPE_MEMBER_DETAIL){
				try{
					String result = (String)resultObj;
					JSONObject obj = new JSONObject(result);
		        	mgr.setData(PreferenceMgr.USER_EMAIL_KEY, obj.getString("userEmail"));
		        	mgr.setData(PreferenceMgr.USER_PASSWORD_KEY, obj.getString("userPassword"));
		        	mgr.setData(PreferenceMgr.USER_NAME_KEY,  obj.getString("userName"));
		        	mgr.setData(PreferenceMgr.USER_DESCRIPT_KEY, obj.getString("userDescription"));
		        	mgr.setData(PreferenceMgr.USER_AGE_KEY, obj.getString("userAge"));
		        	mgr.setData(PreferenceMgr.USER_SEX_KEY, obj.getString("userSex"));
		        	mgr.setData(PreferenceMgr.PHONE_NUMBER_KEY,obj.getString("userPhoneNo"));
		        	
		        	
		            Bitmap Result = null;
		            try {
		                URL url = new URL("http://www.typoong.com/upload/"+mgr.getData(PreferenceMgr.USER_EMAIL_KEY, "")+"_image.jpg");
		                //make bitmap
		                Result = BitmapFactory.decodeStream(url.openStream());            
		            } catch (MalformedURLException e) {
		                Result = null;
		            } catch (IOException e) {
		                Result = null;
		            }
		            if(Result!=null)	img.setImageBitmap(Result);
		    		phone.setText(mgr.getData(PreferenceMgr.PHONE_NUMBER_KEY, ""));
		    		email.setText(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
		    		name.setText(mgr.getData(PreferenceMgr.USER_NAME_KEY, ""));
		    		age.setText(mgr.getData(PreferenceMgr.USER_AGE_KEY, ""));
		    		descript.setText(mgr.getData(PreferenceMgr.USER_DESCRIPT_KEY, ""));
		    		if("M".equals(mgr.getData(PreferenceMgr.USER_SEX_KEY, "M")))
		    			sex_m.setChecked(true);
		    		else
		    			sex_f.setChecked(true);
				}catch(Exception e){
					e.printStackTrace();
				}
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_MEMBER_UPDATE){
				ServerComunicationUtil.showNotify(getString(R.string.toast_update_success), this);
		    	if(password != null){
		    		mgr.setData(PreferenceMgr.USER_PASSWORD_KEY, dto.getUserPassword());
		    	}
		    	mgr.setData(PreferenceMgr.USER_NAME_KEY, dto.getUserName());
		    	mgr.setData(PreferenceMgr.USER_DESCRIPT_KEY, dto.getUserDescription());
			}
		}
		super.onSyncComplete(resultCode, dto, resultObj);
	}
}
